<template>
  <div>
    <!-- 面包屑视图区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        title="注意:只允许为三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品名称：</span>
          <!-- 选择商品级联的选择框 -->
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cateProps"
            clearable
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs
        v-model="activeName"
        @tab-click="handleTabClick"
      >
        <el-tab-pane
          label="动态参数"
          name="many"
        >
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="isAddVisible=true"
          >添加参数</el-button>
          <!-- 动态参数的表格 -->
          <el-table
            :data="manyTableData"
            stripe
            border
          >
            <el-table-column type="expand"></el-table-column>
            <el-table-column
              type="index"
              label="#"
            ></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编 辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                >删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性的表格 -->
        <el-tab-pane
          label="静态属性"
          name="only"
        >
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="isAddVisible=true"
          >添加属性</el-button>
          <el-table
            :data="onlyTableData"
            stripe
            border
          >
            <el-table-column type="expand"></el-table-column>
            <el-table-column
              type="index"
              label="#"
            ></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编 辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                >删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加 对话框 -->
    <el-dialog
      :title="isOnlyOrMany+ '添加'"
      :visible.sync="isAddVisible"
      width="50%"
      center
      @closed="addCateClosed"
    >
      <el-form
        :model="addCateForm"
        ref="addCateFormRef"
        label-width="120px"
        :rules="addCateFormRules"
      >
        <el-form-item
          :label="'添加'+ isOnlyOrMany"
          prop="attr_name"
        >
          <el-input v-model="addCateForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="isAddVisible=false">取 消</el-button>
        <el-button
          type="primary"
          @click="postAddCateForm"
        >提 交</el-button>
      </span>
    </el-dialog>
    <!-- 修改 对话框 -->
    <el-dialog
      :title="'编辑' + isOnlyOrMany"
      :visible.sync="isEditVisible"
      width="50%"
      center
      @closed="editCateClosed"
    >
      <el-form
        :model="editCateForm"
        ref="editCateFormRef"
        label-width="120px"
        :rules="editCateFormRules"
      >
        <el-form-item
          :label="'编辑'+ isOnlyOrMany"
          prop="attr_name"
        >
          <el-input v-model="editCateForm.attr_name">
          </el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="isEditVisible=false">取 消</el-button>
        <el-button
          type="primary"
          @click="postEditCateForm"
        >提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      cateList: [],
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 选中项的数组
      selectedCateKeys: [],
      // 被激活页签的名称
      activeName: 'many',
      // 动态属性数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],
      isAddVisible: false,
      isEditVisible: false,
      addCateForm: {
        attr_id: '',
        attr_name: '',
        attr_sel: ''
      },
      // 修改的表单对象
      editCateForm: {
        attr_id: '',
        attr_name: ''
      },
      addCateFormRules: {
        attr_name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      editCateFormRules: {
        attr_name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类列表失败!')
      }
      this.cateList = res.data
    },
    // 级联选择框选中项变化， 会触发这个函数
    handleChange () {
      this.getParamsData()
    },
    // 页签点击事件的处理函数
    handleTabClick () {
      this.getParamsData()
    },

    // 获取参数
    async getParamsData () {
      // 只允许选中第三级
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return 0
      }
      // 选中的是三级分类
      const { data: res } = await this.$http.get(`categories/${this.isCateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类参数失败!')
      }
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    addCateClosed () {
      this.$refs.addCateFormRef.resetFields()
    },
    // 修改商品对话框关闭时触发
    editCateClosed () {
      this.$refs.editCateFormRef.resetFields()
    },
    // 提交添加商品的表单
    async postAddCateForm () {
      const { data: res } = await this.$http.post(`categories/${this.isCateId}/attributes`, { attr_name: this.addCateForm.attr_name, attr_sel: this.activeName })
      if (res.meta.status !== 201) {
        return this.$message.error('创建失败!')
      }
      this.getParamsData()
      this.isAddVisible = false
    },
    async showEditDialog (attrid) {
      this.isEditVisible = true
      this.editCateForm.attr_id = attrid
      const { data: res } = await this.$http.get(`categories/${this.isCateId}/attributes/${attrid}`, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) {
        this.$message.error('获取失败!')
      }
      this.editCateForm.attr_name = res.data.attr_name
    },
    // 添加动态参数或者静态属性
    postEditCateForm () {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写完整信息')
        }
        const { data: res } = await this.$http.put(`categories/${this.isCateId}/attributes/${this.editCateForm.attr_id}`, {
          attr_name: this.editCateForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) {
          return this.$message.error('更新失败!')
        }
        this.getParamsData()
        this.$message.success('更新成功!')
        this.isEditVisible = false
      })
    },
    // 删除 动态参数 静态属性
    async deleteParams (attrid) {
      const confirm = await this.$confirm(`此操作将永久删除${this.isOnlyOrMany}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirm !== 'confirm') {
        return 0
      }
      const { data: res } = await this.$http.delete(`categories/${this.isCateId}/attributes/${attrid}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败!')
      }
      this.getParamsData()
      this.$message.success('删除成功!')
    }
  },
  created () {
    this.getCateList()
  },
  // 计算属性
  computed: {
    // 如果按钮需要被禁用，而返回true，否则为false
    isBtnDisabled () {
      if (this.selectedCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 获得选中商品的id
    isCateId () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 判断是动态参数还是静态属性
    isOnlyOrMany () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 15px;
}
.el-table {
  margin-top: 15px;
}
</style>
